package com.example.cardmatchinggame;

import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class GameActivity extends AppCompatActivity {
    private CardMatchingGame game;
    private CardAdapter adapter;
    private TextView tvScore;
    private RecyclerView recyclerView;
    private int cardCount = 24;
    private int gameMode = 2; // 默认双卡模式

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game);

        tvScore = findViewById(R.id.tv_score);
        recyclerView = findViewById(R.id.recycler_view);
        Button btnReset = findViewById(R.id.btn_reset);

        // 根据屏幕方向设置卡片数量
        updateCardCount();

        // 初始化游戏
        initGame();

        btnReset.setOnClickListener(v -> resetGame());
    }

    private void updateCardCount() {
        int orientation = getResources().getConfiguration().orientation;
        if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
            // 横屏：使用三卡模式，24张卡片
            cardCount = 24;
            gameMode = 3;
        } else {
            // 竖屏：使用双卡模式，24张卡片
            cardCount = 24;
            gameMode = 2;
        }
    }

    private void initGame() {
        game = new CardMatchingGame(cardCount, gameMode);
        
        // 设置 RecyclerView
        int spanCount = getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE ? 6 : 4;
        GridLayoutManager layoutManager = new GridLayoutManager(this, spanCount);
        recyclerView.setLayoutManager(layoutManager);

        adapter = new CardAdapter(game, position -> {
            game.chooseCardAtIndex(position);
            updateUI();
            
            // 延迟翻回未匹配的卡片
            new Handler().postDelayed(() -> {
                adapter.notifyDataSetChanged();
            }, 500);
        });
        
        recyclerView.setAdapter(adapter);
        updateUI();
    }

    private void updateUI() {
        tvScore.setText(getString(R.string.score, game.getScore()));
        adapter.notifyDataSetChanged();
    }

    private void resetGame() {
        game.reset();
        updateUI();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        updateCardCount();
        initGame();
    }
}
